package ss;

import mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get...");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post");
        String key = req.getParameter("key");
        if (key!=null){
            System.out.println("key不为空");

            HttpSession session = req.getSession();

            session.invalidate();//注销该request的所有session

            req.getRequestDispatcher("/login.html").forward(req,resp);
        }
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username);
        System.out.println(password);

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.select(username, password);

        System.out.println(user);

        if (user!=null){
            System.out.println("登录成功");
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            req.getRequestDispatcher("/LoginSuccess.jsp").forward(req,resp);
            HttpSession session1 = req.getSession();
            ServletContext servletContext = session1.getServletContext();
            Integer onlineCount = (Integer) servletContext.getAttribute("onlineCount");
            onlineCount++;
            servletContext.setAttribute("onlineCount",onlineCount);
        }else {
            System.out.println("登录失败");

            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("登录失败");
            req.getRequestDispatcher("/login.html").forward(req,resp);
        }

        sqlSession.close();
    }
}
